﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Threading;
using System.Diagnostics;

namespace PascalTriangle
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        TriangleContainer container;
        

        private void Form1_Load(object sender, EventArgs e)
        {

        }

        private void exitButton_Click(object sender, EventArgs e)
        {
            Application.Exit();
        }

        private void runButton_Click(object sender, EventArgs e)
        {
            int lvl = (int)levelNumeric.Value;
            int thr = (int)threadsNumeric.Value;
            bool allEnded = true;

            Semaphore globalSemaphore = new Semaphore(thr, thr);
            container = new TriangleContainer(lvl);

            Solver[] solvers = new Solver[thr];
            Thread[] threads = new Thread[thr];

            for (int i = 0; i < thr; i++)
            {
                solvers[i] = new Solver(container, i, globalSemaphore);
                threads[i] = new Thread(new ThreadStart(solvers[i].Run));
            }

            Stopwatch sw = new Stopwatch();
            sw.Start();

            foreach (Thread t in threads)
            {
                t.Start();
            }

            do
            {
                allEnded = true;

                foreach (Thread t in threads)
                {
                    if (t.IsAlive)
                    {
                        allEnded = false;
                        break;
                    }
                }
            } while (!allEnded);

            sw.Stop();

            float delta = sw.ElapsedMilliseconds;

            string s = container.LastLine();
            textBox.Text = s;
            textBox.AppendText("\r\n" + "Total time:" + delta.ToString() + "ms");

            foreach (Solver solver in solvers)
            {
                textBox.AppendText("\r\n" + "Thread " + solver.ID + " points: " + solver.Points.ToString());
            }
        }
    }
}
